package com.atguigu.gulimall.seckill.service.impl;

import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimall.seckill.feign.CouponFeifnService;
import com.atguigu.gulimall.seckill.feign.ProductFeifnService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionEntity;
import com.atguigu.gulimall.seckill.vo.SeckillSkuRelationEntity;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeifnService couponFeifnService;
    @Autowired
    ProductFeifnService productFeifnService;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKU_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHRE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R latest3DaysSession = couponFeifnService.getLatest3DaysSession();
        if (latest3DaysSession.getCode() == 0) {
            List<SeckillSessionEntity> data = R.toListPoJo(latest3DaysSession.get("data"), SeckillSessionEntity.class);
            log.debug("远程调用成功:{}", data);
            if (data == null || data.isEmpty()) {
                return;
            }
            //远程调用成功
            saveSessionInfos(data);
            saveSessionSkuInfos(data);
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        long time = new Date().getTime();
        List<SeckillSkuRedisTo> seckillSkuRedisTos = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String[] s = key.replace(SESSION_CACHE_PREFIX, "").split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                if (range == null || range.isEmpty()) {
                    continue;
                }
                BoundHashOperations<String, String, SeckillSkuRedisTo> hashOps = redisTemplate.boundHashOps(SKU_CACHE_PREFIX);
                List<SeckillSkuRedisTo> onlySeckillSkuRedisTos = hashOps.multiGet(range);
                if (onlySeckillSkuRedisTos != null) {
                    onlySeckillSkuRedisTos.forEach(item -> item.setRandomCode(null));
                    seckillSkuRedisTos.addAll(onlySeckillSkuRedisTos);
                }
            }
        }
        return seckillSkuRedisTos;
    }

    @Override
    public SeckillSkuRedisTo getSeckillSkuInfo(Long skuId) {
        BoundHashOperations<String, String, SeckillSkuRedisTo> hashOps = redisTemplate.boundHashOps(SKU_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        long now = new Date().getTime();
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String regx = "\\d+_" + skuId;
                if (Pattern.matches(regx, key)) {
                    SeckillSkuRedisTo seckillSkuRedisTo = hashOps.get(key);
                    if (seckillSkuRedisTo != null && now <= seckillSkuRedisTo.getEndTime()) {
                        return seckillSkuRedisTo;
                    } else if (seckillSkuRedisTo != null) {
                        seckillSkuRedisTo.setRandomCode(null);
                        return seckillSkuRedisTo;
                    }

                }
            }
        }

        return null;
    }

    /**
     * 秒杀逻辑
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberEntityVo memberEntityVo = LoginUserInterceptor.threadLocal.get();
        BoundHashOperations<String, String, SeckillSkuRedisTo> hashOps = redisTemplate.boundHashOps(SKU_CACHE_PREFIX);
        SeckillSkuRedisTo seckillSkuRedisTo = hashOps.get(killId);
        if (seckillSkuRedisTo != null && seckillSkuRedisTo.getRandomCode().equals(key)) {
            long now = new Date().getTime();
            if (now >= seckillSkuRedisTo.getStartTime() && now <= seckillSkuRedisTo.getEndTime()) {
                Integer stock = (Integer)redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHRE + key);
                if (stock != null && stock >= num) {
                    String redisKey = memberEntityVo.getId().toString() + "_" + killId;
                    Boolean b = redisTemplate.opsForValue().setIfAbsent(redisKey, num, seckillSkuRedisTo.getEndTime() - now, TimeUnit.MILLISECONDS);
                    if (b) {
                        //没有买过
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHRE + key);
                        boolean b1 = false;
                        try {
                            b1 = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                        } catch (InterruptedException e) {
                            log.error("没有拿到信号量:{}",killId);
                        }
                        if (b1) {
                            String orderSn = IdWorker.getTimeId();
                            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                            seckillOrderTo.setOrderSn(orderSn);
                            seckillOrderTo.setPromtionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                            seckillOrderTo.setSkuId(seckillSkuRedisTo.getSkuId());
                            seckillOrderTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                            seckillOrderTo.setNum(num);
                            seckillOrderTo.setMemberId(memberEntityVo.getId());
                            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.other", seckillOrderTo);
                            return orderSn;
                        }
                    }
                }
            }
        }
        log.info("抢购失败");
        return null;
    }

    private void saveSessionSkuInfos(List<SeckillSessionEntity> data) {
        for (SeckillSessionEntity datum : data) {
            BoundHashOperations<String, Object, Object> stringObjectObjectBoundHashOperations = redisTemplate.boundHashOps(SKU_CACHE_PREFIX);
            for (SeckillSkuRelationEntity relationSkus : datum.getRelationSkus()) {
                String key = relationSkus.getPromotionSessionId() + "_" + relationSkus.getSkuId().toString();
                if (Boolean.TRUE.equals(stringObjectObjectBoundHashOperations.hasKey(key))) {
                    continue;
                }
                SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                //活动信息，价格信息
                BeanUtils.copyProperties(relationSkus, seckillSkuRedisTo);
                R spuInfoBySkuId = productFeifnService.getSkuInfoBySkuId(relationSkus.getSkuId());
                if (spuInfoBySkuId.getCode() == 0) {
                    SkuInfoVo sku = R.toPoJo(spuInfoBySkuId.get("skuInfo"), SkuInfoVo.class);
                    seckillSkuRedisTo.setSkuInfo(sku);
                }
                seckillSkuRedisTo.setStartTime(datum.getStartTime().getTime());
                seckillSkuRedisTo.setEndTime(datum.getEndTime().getTime());
                //随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                seckillSkuRedisTo.setRandomCode(token);
                //秒杀的信号量(库存)
                RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHRE + token);
                semaphore.trySetPermits(relationSkus.getSeckillCount());

                stringObjectObjectBoundHashOperations.put(key, seckillSkuRedisTo);
            }
        }
    }

    private void saveSessionInfos(List<SeckillSessionEntity> data) {
        for (SeckillSessionEntity datum : data) {
            long start = datum.getStartTime().getTime();
            long end = datum.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + start + "_" + end;
            Boolean hasKey = stringRedisTemplate.hasKey(key);
            if (Boolean.FALSE.equals(hasKey)) {
                List<String> skuIds = datum.getRelationSkus().stream()
                        .map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString())
                        .collect(Collectors.toList());
                log.debug("准备导入数据:{}", skuIds);
                if (!skuIds.isEmpty())
                    stringRedisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        }
    }
}
